import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { ConfigModule, ConfigService } from "@nestjs/config";
import * as path from "path";
import { EnvNameEnum } from "../env";

/**
 * TypeORM 模块
 */
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      // 导入配置模块，否则无法使用 ConfigService
      imports: [ConfigModule],
      // 注入 ConfigService 到创建数据库连接的工厂函数中
      inject: [ConfigService],
      // 工厂函数，根据环境变量配置创建数据库连接
      useFactory: (configService: ConfigService) => ({
        type: configService.get<'mysql' | 'mariadb'>(EnvNameEnum.DB_TYPE),
        host: configService.get<string>(EnvNameEnum.DB_HOST),
        port: configService.get<number>(EnvNameEnum.DB_PORT),
        username: configService.get<string>(EnvNameEnum.DB_USERNAME),
        password: configService.get<string>(EnvNameEnum.DB_PASSWORD),
        database: configService.get<string>(EnvNameEnum.DB_DATABASE),
        // 实体文件路径
        entities: [path.join(__dirname, '../../../**/entities/*{.ts,.js}')],
        logging: true,
        logger: "advanced-console",
        loggerLevel: 'info'
      })
    })
  ]
})
export class TypeormModule {
}
